import { RollupOptions } from 'rollup';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel';
import typescript from '@rollup/plugin-typescript';
import htmlTemplate from 'rollup-plugin-generate-html-template';
import replace from '@rollup/plugin-replace';
import serve from 'rollup-plugin-serve';
import livereload from 'rollup-plugin-livereload';
import clear from 'rollup-plugin-clear';
import postcss from 'rollup-plugin-postcss';
import image from '@rollup/plugin-image';
import alias from '@rollup/plugin-alias';
import { fileURLToPath } from 'node:url';
import terser from '@rollup/plugin-terser';
import { visualizer } from 'rollup-plugin-visualizer';

const config: RollupOptions = {
  input: 'src/main.tsx',
  output: {
    dir: 'dist',
    format: 'esm',
    name: 'rollupDemo',
    sourcemap: true,
    entryFileNames: '[name]-[hash].js',
    chunkFileNames: 'chunk/chunk-[name].[hash].js',
    //  不做分包
    // manualChunks: {
    //   react: ["react", "react-dom"],
    // },
    // 对打包产物  进行压缩
    plugins: [terser()],
    globals: {
      // 将 导入的模块 react 和 react-dom 替换成全局变量
      react: 'React',
      'react-dom': 'ReactDOM',
    },
    paths: {
      // 将 全局变量 react 和 react-dom  通过script标签 引入cdn
      react: 'https://cdn.jsdelivr.net/npm/react@18.2.0/+esm',
      'react-dom': 'https://cdn.jsdelivr.net/npm/react-dom@18.2.0/+esm',
    },
  },
  external: ['react', 'react-dom'], // 不去解析 react 和 react-dom
  plugins: [
    nodeResolve(),
    commonjs(),
    typescript(),
    babel({
      babelHelpers: 'runtime',
      include: 'src/**',
      exclude: 'node_modules/**',
      extensions: ['.js', '.jsx', '.ts', '.tsx'],
    }),
    // 将 全局变量 替换一下
    replace({
      // 需要将字符串做一下替换，不然会报错：process is not defined
      preventAssignment: true,
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
    alias({
      entries: [
        {
          find: '@',
          replacement: fileURLToPath(new URL('src', import.meta.url)), // 差不多 意思 就是 path.resolve(__dirname, 'src')
        },
      ],
    }),

    serve('dist'),
    livereload('src'),
    clear({
      targets: ['dist'],
    }),
    postcss({
      extensions: ['.css'], // 将scss 解析成css
      extract: true, // 将css 提取到dist目录下
      modules: true, // 增加css的模块化支持
    }),
    htmlTemplate({
      template: 'public/index.html',
      target: 'dist/index.html',
      attrs: ['type="module"'],
    }),
    image(),
    visualizer(), //  可视化分析 Rollup 打包结果‌
  ],
};

export default config;
